<template>
  <div class="nginx-debug">
    <h1>Nginx环境诊断页面</h1>
    <p>专门用于诊断Nginx环境中的侧边栏切换问题</p>
    
    <div class="debug-sections">
      <!-- 基础环境检测 -->
      <div class="debug-section">
        <h3>基础环境检测</h3>
        <div class="info-grid">
          <div class="info-item">
            <strong>当前URL:</strong> {{ currentUrl }}
          </div>
          <div class="info-item">
            <strong>Hash路由:</strong> {{ hasHashRouter ? '是' : '否' }}
          </div>
          <div class="info-item">
            <strong>History路由:</strong> {{ hasHistoryRouter ? '是' : '否' }}
          </div>
          <div class="info-item">
            <strong>服务器环境:</strong> {{ isServer ? '是' : '否' }}
          </div>
          <div class="info-item">
            <strong>LocalStorage可用:</strong> {{ localStorageAvailable ? '是' : '否' }}
          </div>
        </div>
      </div>
      
      <!-- 侧边栏状态检测 -->
      <div class="debug-section">
        <h3>侧边栏状态检测</h3>
        <div class="info-grid">
          <div class="info-item">
            <strong>当前状态:</strong> {{ sidebarState }}
          </div>
          <div class="info-item">
            <strong>LocalStorage值:</strong> {{ localStorageValue }}
          </div>
          <div class="info-item">
            <strong>切换次数:</strong> {{ toggleCount }}
          </div>
          <div class="info-item">
            <strong>最后切换时间:</strong> {{ lastToggleTime }}
          </div>
        </div>
      </div>
      
      <!-- 性能检测 -->
      <div class="debug-section">
        <h3>性能检测</h3>
        <div class="info-grid">
          <div class="info-item">
            <strong>页面加载时间:</strong> {{ pageLoadTime }}ms
          </div>
          <div class="info-item">
            <strong>内存使用:</strong> {{ memoryUsage }}
          </div>
          <div class="info-item">
            <strong>CPU核心数:</strong> {{ cpuCores }}
          </div>
          <div class="info-item">
            <strong>网络连接:</strong> {{ networkInfo }}
          </div>
        </div>
      </div>
      
      <!-- 错误检测 -->
      <div class="debug-section">
        <h3>错误检测</h3>
        <div v-if="errors.length === 0" class="no-errors">
          暂无错误
        </div>
        <div v-else class="error-list">
          <div v-for="(error, index) in errors" :key="index" class="error-item">
            <div class="error-type">{{ error.type }}</div>
            <div class="error-message">{{ error.message }}</div>
            <div class="error-time">{{ error.time }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 测试按钮 -->
    <div class="test-buttons">
      <button @click="testSidebarToggle" :disabled="isToggling">
        {{ isToggling ? '切换中...' : '测试侧边栏切换' }}
      </button>
      <button @click="testLocalStorage">测试LocalStorage</button>
      <button @click="testPerformance">测试性能</button>
      <button @click="clearErrors">清除错误</button>
      <button @click="resetSidebar">重置侧边栏</button>
    </div>
    
    <!-- 测试结果 -->
    <div class="test-results">
      <h3>测试结果</h3>
      <div v-for="(result, index) in testResults" :key="index" :class="['test-result', result.type]">
        {{ result.time }}: {{ result.message }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const currentUrl = ref('')
const hasHashRouter = ref(false)
const hasHistoryRouter = ref(false)
const isServer = ref(false)
const localStorageAvailable = ref(false)
const sidebarState = ref('未知')
const localStorageValue = ref('未知')
const toggleCount = ref(0)
const lastToggleTime = ref('')
const pageLoadTime = ref(0)
const memoryUsage = ref('未知')
const cpuCores = ref(0)
const networkInfo = ref('未知')
const errors = ref([])
const testResults = ref([])
const isToggling = ref(false)

const startTime = performance.now()

onMounted(() => {
  // 基础环境检测
  currentUrl.value = window.location.href
  hasHashRouter.value = window.location.hash !== ''
  hasHistoryRouter.value = window.location.pathname !== '/'
  isServer.value = window.location.hostname !== 'localhost' && 
                   window.location.hostname !== '127.0.0.1'
  
  // LocalStorage检测
  try {
    localStorage.setItem('test', 'test')
    localStorage.removeItem('test')
    localStorageAvailable.value = true
  } catch (error) {
    localStorageAvailable.value = false
    addError('LocalStorage不可用', error.message)
  }
  
  // 侧边栏状态检测
  try {
    const savedState = localStorage.getItem('sidebarCollapsed')
    localStorageValue.value = savedState || '未设置'
    sidebarState.value = savedState === 'true' ? '收起' : '展开'
  } catch (error) {
    addError('读取侧边栏状态失败', error.message)
  }
  
  // 性能检测
  pageLoadTime.value = Math.round(performance.now() - startTime)
  
  if (navigator.hardwareConcurrency) {
    cpuCores.value = navigator.hardwareConcurrency
  }
  
  if (navigator.connection) {
    networkInfo.value = `${navigator.connection.effectiveType || 'unknown'} (${navigator.connection.downlink || 'unknown'}Mbps)`
  }
  
  // 内存检测
  if (performance.memory) {
    const memory = performance.memory
    memoryUsage.value = `${Math.round(memory.usedJSHeapSize / 1024 / 1024)}MB / ${Math.round(memory.totalJSHeapSize / 1024 / 1024)}MB`
  }
  
  addTestResult('页面加载完成', 'success')
  
  // 监听错误
  window.addEventListener('error', handleError)
  window.addEventListener('unhandledrejection', handleUnhandledRejection)
})

onUnmounted(() => {
  window.removeEventListener('error', handleError)
  window.removeEventListener('unhandledrejection', handleUnhandledRejection)
})

const handleError = (event) => {
  addError('JavaScript错误', `${event.message} (${event.filename}:${event.lineno})`)
}

const handleUnhandledRejection = (event) => {
  addError('未处理的Promise拒绝', event.reason)
}

const addError = (type, message) => {
  errors.value.push({
    type,
    message,
    time: new Date().toLocaleTimeString()
  })
}

const addTestResult = (message, type = 'info') => {
  testResults.value.push({
    time: new Date().toLocaleTimeString(),
    message,
    type
  })
}

const testSidebarToggle = async () => {
  if (isToggling.value) return
  
  isToggling.value = true
  addTestResult('开始测试侧边栏切换', 'info')
  
  try {
    // 模拟侧边栏切换
    const event = new CustomEvent('toggle-sidebar')
    window.dispatchEvent(event)
    
    // 更新状态
    toggleCount.value++
    lastToggleTime.value = new Date().toLocaleTimeString()
    
    // 检查LocalStorage
    setTimeout(() => {
      try {
        const newState = localStorage.getItem('sidebarCollapsed')
        localStorageValue.value = newState || '未设置'
        sidebarState.value = newState === 'true' ? '收起' : '展开'
        addTestResult('侧边栏切换测试成功', 'success')
      } catch (error) {
        addTestResult(`侧边栏状态检查失败: ${error.message}`, 'error')
      } finally {
        isToggling.value = false
      }
    }, 200)
    
  } catch (error) {
    addTestResult(`侧边栏切换测试失败: ${error.message}`, 'error')
    isToggling.value = false
  }
}

const testLocalStorage = () => {
  try {
    const testKey = 'nginx-debug-test'
    const testValue = `test-${Date.now()}`
    
    localStorage.setItem(testKey, testValue)
    const retrievedValue = localStorage.getItem(testKey)
    localStorage.removeItem(testKey)
    
    if (retrievedValue === testValue) {
      addTestResult('LocalStorage测试成功', 'success')
    } else {
      addTestResult('LocalStorage测试失败: 值不匹配', 'error')
    }
  } catch (error) {
    addTestResult(`LocalStorage测试失败: ${error.message}`, 'error')
  }
}

const testPerformance = () => {
  try {
    const start = performance.now()
    
    // 执行一些计算密集型操作
    let result = 0
    for (let i = 0; i < 1000000; i++) {
      result += Math.random()
    }
    
    const end = performance.now()
    const duration = Math.round(end - start)
    
    addTestResult(`性能测试完成: ${duration}ms (结果: ${result.toFixed(2)})`, 'success')
  } catch (error) {
    addTestResult(`性能测试失败: ${error.message}`, 'error')
  }
}

const clearErrors = () => {
  errors.value = []
  addTestResult('错误记录已清除', 'success')
}

const resetSidebar = () => {
  try {
    localStorage.removeItem('sidebarCollapsed')
    sidebarState.value = '展开'
    localStorageValue.value = '未设置'
    toggleCount.value = 0
    lastToggleTime.value = ''
    addTestResult('侧边栏状态已重置', 'success')
  } catch (error) {
    addTestResult(`重置侧边栏失败: ${error.message}`, 'error')
  }
}
</script>

<style scoped>
.nginx-debug {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}

h1 {
  color: #333;
  text-align: center;
  margin-bottom: 30px;
}

.debug-sections {
  display: grid;
  gap: 20px;
  margin-bottom: 30px;
}

.debug-section {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  background: #f9f9f9;
}

.debug-section h3 {
  margin-top: 0;
  color: #666;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
}

.info-grid {
  display: grid;
  gap: 8px;
}

.info-item {
  background: white;
  padding: 8px;
  border-radius: 4px;
  font-size: 14px;
}

.error-list {
  max-height: 300px;
  overflow-y: auto;
}

.error-item {
  background: #fff5f5;
  padding: 10px;
  margin: 5px 0;
  border-radius: 4px;
  border-left: 3px solid #dc3545;
}

.error-type {
  font-weight: bold;
  color: #dc3545;
  margin-bottom: 5px;
}

.error-message {
  font-size: 14px;
  margin-bottom: 5px;
}

.error-time {
  font-size: 12px;
  color: #666;
}

.no-errors {
  text-align: center;
  color: #28a745;
  font-style: italic;
}

.test-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

button {
  padding: 10px 20px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover:not(:disabled) {
  background: #0056b3;
}

button:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.test-results {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  background: #f8f9fa;
  max-height: 300px;
  overflow-y: auto;
}

.test-result {
  margin: 5px 0;
  padding: 5px;
  border-radius: 4px;
}

.test-result.success {
  color: #28a745;
  background: #d4edda;
}

.test-result.error {
  color: #dc3545;
  background: #f8d7da;
}

.test-result.info {
  color: #17a2b8;
  background: #d1ecf1;
}
</style> 